import hashlib
import os
import socket
import sys

from PySide6.QtWidgets import QApplication


from config import DATA_PATH, APP_VERSION
from utils.update import UpdateProgress
from windows.activation_dialog import ActivationDialog
from windows.main_window import MyMainWindow

# 程序入口
if __name__ == "__main__":
    # 初始化QApplication，界面展示要包含在QApplication初始化之后，结束之前
    app = QApplication(sys.argv)
    # host_name = socket.gethostname()
    host_name = 'jerry' + os.getlogin()
    host_name_md5 = hashlib.md5(host_name.encode()).hexdigest()
    if not os.path.exists(DATA_PATH):
        os.makedirs(DATA_PATH)
    refer_path = os.path.join(DATA_PATH, "refer.txt")
    # 检查 refer.txt 文件是否存在，如果不存在则创建
    if not os.path.exists(refer_path):
        with open(refer_path, "w", encoding="utf-8") as f:
            pass
    # 检查 refer.txt 文件是否存在且已激活
    if os.path.exists(refer_path):
        with open(refer_path, "r") as f:
            status = f.read().strip()
            if status != host_name_md5:
                # 创建并显示激活窗口
                activation_dialog = ActivationDialog(host_name_md5)
                activation_dialog.exec()

    # 初始化并展示我们的界面组件
    main_window = MyMainWindow(app)
    main_window.setWindowTitle("Fu Reader " + APP_VERSION)
    # 处理命令行参数
    file_to_open = None
    if len(sys.argv) > 1:
        file_to_open = sys.argv[1]
        main_window.start_open_file_thread(file_to_open)
    # apply_stylesheet(app, theme='./theme/my_light_theme.xml', css_file='./theme/my.css')
    # 设置全局按钮样式表
    app.setStyleSheet("""
    QPushButton {
        background-color: #FFFFFF;
        color: #333333;
        border: 1px solid #E5E5E5;
        border-radius: 4px;
        padding: 6px 12px;
        height: 15px;
    }

    QPushButton:hover {
        background-color: #F5F5F5;
        border: 1px solid #0077FF;
        border-radius: 4px;
    }

    QPushButton:pressed {
        background-color: #E0E0E0;
        border-color: #B0B0B0;
        border-radius: 4px;
    }
        QPushButton:checked {
        background-color: #F5F5F5;
        border: 1px solid #0077FF;
        border-radius: 4px;
    }
    """)
    main_window.show()

    app_exec = app.exec()
    # 结束QApplication
    sys.exit(app_exec)